/**
 * Created by ke.ouyang on 19/10/29
 * Email ke.ouyang@huilianyi.com
 */
import React from 'react';
import {connect} from 'react-redux';
import moment from 'moment';
import {messages, deepCopy} from 'share/common';
import 'styles/enterprise-manage/person-manage/person-info-display/person-info-display.scss';
import PIDService from 'containers/enterprise-manage/person-manage/person-info-display/person-info-display.service';
import menuRoute from 'routes/menuRoute';
import {Button, Icon, message, Modal, Form, Row, Col, Checkbox, Input, Popover} from 'antd';
const FormItem = Form.Item;
import IPhoneX from 'components/iphone-x';
import Condition from 'components/condition';
const {If} = Condition;
//Img
import maleImg from 'images/user-male.png';
import femaleImg from 'images/user-female.png';
import unknowImg from 'images/user-unknow.png';
import emailImg from 'images/personal-setting/email.png';
import jobIdImg from 'images/personal-setting/jobId.png';
import phoneImg from 'images/personal-setting/phone.png';
import arrowImg from 'images/personal-setting/arrow.png';


class PersonInfoDisplay extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true, //保存按钮是否 loading
      avatar: '', //用户自己的头像
      userInfo: '', //用户详情接口 获取到的信息
      basicShowMap: { //基础显示隐藏控制
        'fullName': true,
        'employeeID': true,
        'mobile': true,
        'email': true,
        'employeeType': true,
        'directManagerName': false,
        'gender': false,
        'birthday': false,
        'entryTime': false
      },
      jobInfoShowMap: { //岗位信息显示隐藏控制
        'position': true,
        'companyName': true,
        'departmentName': true,
        'duty': true,
        'rank': true
      },
      extendShowMap: {}, //扩展字段显示隐藏控制
      data: [], //储存 checkBox 接口拿到的data
      basicInitValue: [],
      jobInfoInitValue: [],
      extendInitValue: [],
      basicOption: [
        {label:messages('basic-5.key95')/*姓名*/ , value: 'fullName'},
        {label:messages('common.user.id')/*工号*/ , value: 'employeeID'},
        {label:messages('basic-5.key380')/*手机*/ , value: 'mobile'},
        {label:messages('basic-5.key162')/*邮箱*/ , value: 'email'},
        {label:messages('basic-5.key382')/*人员类型*/ , value: 'employeeType'},
        {label:messages('basic-5.key278')/*直属领导*/ , value: 'directManagerName'},
        {label:messages('basic-5.key283')/*性别*/ , value: 'gender'},
        {label:messages('basic-5.key282')/*生日*/ , value: 'birthday'},
        {label:messages('basic-5.key281')/*入职时间*/ , value: 'entryTime'},
      ],
      jobInfoOption: [
        {label:messages('basic-5.key163')/*职位*/ , value: 'position'},
        {label:messages('basic-5.key1')/*公司*/ , value: 'companyName'},
        {label:messages('common.department')/*部门*/ , value: 'departmentName'},
        {label:messages('basic-5.key279')/*职务*/ , value: 'duty'},
        {label:messages('basic-5.key280')/*级别*/ , value: 'rank'},
      ]

    };
  }
  componentDidMount() {
    const { basicShowMap,
      jobInfoShowMap,
      extendShowMap,
      basicInitValue,
      jobInfoInitValue,
      extendInitValue,
      loading} = this.state;
    PIDService.getSetList().then((res)=> {
      res.data.map((item)=> {
        if (item.fieldType === 'basicInfo') {
          basicShowMap[item.fieldCode] = item.show;
          if(item.show) {
            basicInitValue.push(item.fieldCode);
          }
        } else if (item.fieldType === 'positionInfo') {
          jobInfoShowMap[item.fieldCode] = item.show;
          if(item.show) {
            jobInfoInitValue.push(item.fieldCode);
          }
        } else if (item.fieldType === 'customField') {
          extendShowMap[item.fieldOid] = item.show;
          if(item.show) {
            extendInitValue.push(item.fieldOid);
          }
        }
        this.setState({
          basicShowMap,
          jobInfoShowMap,
          extendShowMap,
          data: res.data,
          basicInitValue,
          jobInfoInitValue,
          extendInitValue
        })
      })
    }).catch((err)=> {
        message.error(messages('common.error')/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/);
    });
    const {user} = this.props;
    PIDService.getPersonDetail(user.userOID)  //获取用户信息
      .then((res) => {
        this.setState({
          userInfo: deepCopy(res.data),
          loading: false
        });
      });
    if (user.avatar === null) {   //设置预览头像
      if (user.gender === 0) {
        this.setState({
          avatar: maleImg
        });
      } else if (user.gender === 1) {
        this.setState({
          avatar: femaleImg
        });
      } else {
        this.setState({
          avatar: unknowImg
        });
      }
    } else {
      this.setState({
        avatar: user.avatar
      });
    }
  }

  //返回上一页
  handleCancel = () => {
    this.context.router.push(menuRoute.getRouteItem('person-manage').url);
  };
  //基础字段 checkbox 数据变化
  handleBasicChange = (value) => {
    const {basicShowMap} = this.state;
    Object.keys(basicShowMap)
      .forEach((key) => {
        return basicShowMap[key] = false;
      });
    value.map((item) => {
      Object.keys(basicShowMap)
        .forEach((key) => {
          if (item === key) {
            return basicShowMap[key] = true;
          }
        });
    });
    this.setState({
      basicShowMap,
    });
  };
  //扩展字段 checkbox 数据变化
  handleExtendChange = (value) => {
    const {extendShowMap} = this.state;
    Object.keys(extendShowMap)
      .forEach((key) => {
        return extendShowMap[key] = false;
      });
    value.map((item) => {
      Object.keys(extendShowMap)
        .forEach((key) => {
          if (item === key) {
            return extendShowMap[key] = true;
          }
        });
    });
    this.setState({
      extendShowMap,
    });
  };
  //岗位信息 checkbox 数据变化
  handleJobInfoChange = (value) => {
    const {jobInfoShowMap} = this.state;
    Object.keys(jobInfoShowMap)
      .forEach((key) => {
        return jobInfoShowMap[key] = false;
      });
    value.map((item) => {
      Object.keys(jobInfoShowMap)
        .forEach((key) => {
          if (item === key) {
            return jobInfoShowMap[key] = true;
          }
        });
    });
    this.setState({
      jobInfoShowMap,
    });
  };
  //点击了保存 发送数据
  handleSubmit = (e) => {
    this.setState({
      loading: true
    });
    const { data } = this.state;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        data.map((item)=> {
          item.show = false;      //先全部置为 false
          if(item.fieldType === 'basicInfo') {
            values.basicField.map((valueIem)=> {
              if(item.fieldCode === valueIem) {
                item.show = true;
              }
            })
          } else if (item.fieldType === 'positionInfo') {
            values.jobInfo.map((valueIem)=> {
              if(item.fieldCode === valueIem) {
                item.show = true;
              }
            })
          } else if (item.fieldType === 'customField') {
            values.extendField.map((valueIem)=> {
              if(item.fieldOid === valueIem) {
                item.show = true;
              }
            })
          }
        });
        PIDService.updateSetList(data).then((res)=> {
          message.success(messages('basic-5.key463')/*保存成功*/);
          this.setState({
            loading: false
          });
        }).catch((err)=> {
          message.error(messages('common.save.filed')/*保存失败*/);
          this.setState({
            loading: false
          });
        })
      }
    });
  };
  //渲染扩展字段 的 checkbox
  renderExtendFieldCheckbox = () => {
    const {userInfo} = this.state;
    let extendField = userInfo.customFormValues;
    return extendField && extendField.map((item) => {
      return (
        <Checkbox value={item.fieldOID}
                  disabled={item.messageKey==='image' ? true : false}>{item.fieldName}</Checkbox>
      );
    });
  };
  //渲染扩展字段
  renderExtendField = () => {
    const { language } = this.props;
    const {userInfo, extendShowMap} = this.state;
    let extendField = userInfo.customFormValues;
    return extendField && extendField.map((item) => {
      if(item.messageKey === 'common.date') {
        return (
          <If value={extendShowMap[item.fieldOID]}>
            <div>
              {item.fieldName + '：' + (item.value ? moment(item.value).format('YYYY/MM/DD') : '-')}
            </div>
          </If>
        );
      } else if (item.messageKey === 'number') {
        let unit = JSON.parse(item.fieldContent);
        let showUnit;
        if (unit.unit.length) {
          if (unit.unitI18n) {
            unit.unitI18n.map((item)=>{
              if (item.language === language.code) {
                if (item.value.length === 0) {
                  showUnit = ' ' + unit.unit;
                } else {
                  showUnit = ' ' + item.value;
                }
              }
            });
          } else {
            showUnit = ' ' + unit.unit;
          }
        } else {
          showUnit = '';
        }
        return (
          <If value={extendShowMap[item.fieldOID]}>
            <div>
              {item.fieldName + '：' + (item.value ?
                (item.value + showUnit) : '-')}
            </div>
          </If>
        );
      } else {
        return (
          <If value={extendShowMap[item.fieldOID]}>
            <div>
              {item.fieldName + '：' + ((item.name || item.showValue || item.value) ? (item.name || item.showValue || item.value) : '-')}
            </div>
          </If>
        );
      }
    });
  };
  //烦的来了…… 渲染 岗位信息
  renderPosition = () => {
    const {userInfo, jobInfoShowMap} = this.state;
    let list = userInfo.companyWithUserJobsDTOList;
    return list && list.map((list) => {
      return (
        <div className="one-company">
          <If value={jobInfoShowMap['companyName']}>
            <div className="company-name">
              <span className="square"></span>
              <span className="name">{list && (list.companyName ? list.companyName : '-')}</span>
            </div>
          </If>
          {list && list.userJobsDTOList.map((item) => {
            return (
              <If
                value={jobInfoShowMap['position'] || jobInfoShowMap['departmentName'] || jobInfoShowMap['duty'] || jobInfoShowMap['rank']}>
                <div
                  className={item.companyMainPosition ? 'single-job-card-main' : 'single-job-card-other'}>
                  <If value={jobInfoShowMap['position']}>
                    <div className="job-title">
                      {item.position}
                    </div>
                  </If>
                  <div className={jobInfoShowMap['position'] ? 'job-detail' : 'job-detail-on'}>
                    {
                      this.renderDetail(item)
                    }
                  </div>
                  <If value={item.companyMainPosition}>
                  <span className="main-stamp">
                    {messages('basic-5.key412')/*主岗*/}
                  </span>
                  </If>
                </div>
              </If>
            );
          })}
        </div>
      );
    });
  };
  renderDetail = (data) => {    //渲染岗位详情字段
    const {jobInfoShowMap} = this.state;
    let departmentName = jobInfoShowMap['departmentName'];
    let duty = jobInfoShowMap['duty'];
    let rank = jobInfoShowMap['rank'];
    let arr = [];
    if (departmentName) {
      arr.push((data.departmentName ? data.departmentName : '-'));
    }
    if (duty) {
      arr.push((data.duty ? data.duty : '-'));
    }
    if (rank) {
      arr.push(data.rank ? data.rank : '-');
    }
    return arr.map(item => item)
      .join(' | ');
  };


  render() {
    const {loading,
      avatar,
      userInfo,
      basicShowMap,
      jobInfoShowMap,
      extendShowMap,
      basicInitValue,
      jobInfoInitValue,
      extendInitValue,
      basicOption,
      jobInfoOption} = this.state;
    const formLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 23},
    };
    const checkboxLayout = {
      marginBottom: '30px'
    };
    const {getFieldDecorator} = this.props.form;
    const hasBasicInfo = (basicShowMap['employeeID'] || basicShowMap['mobile'] || basicShowMap['email']);
    const hasJobsInfo = (jobInfoShowMap['companyName'] || jobInfoShowMap['position'] || jobInfoShowMap['departmentName'] || jobInfoShowMap['duty'] || jobInfoShowMap['rank']);
    const hasOtherInfo = (basicShowMap['employeeType'] || basicShowMap['directManagerName'] || basicShowMap['gender'] || basicShowMap['birthday'] || basicShowMap['entryTime']);
    return (
      <div className="person-info-display-wrap">
        <Row>
          <Col span={15}>
            <Form className="form" onSubmit={this.handleSubmit}>
              <div className="basicField-card">
                <div className="main-title">{messages('basic-5.key464')/*基本字段*/}</div>
                <FormItem {...formLayout}>
                  {
                    getFieldDecorator('basicField', {
                      initialValue: basicInitValue,
                    })(
                      <Checkbox.Group options={basicOption} className="checkbox-group" onChange={this.handleBasicChange}>
                      </Checkbox.Group>
                    )
                  }
                </FormItem>
              </div>
              <If value={JSON.stringify(extendShowMap) !== '{}'}>
                <div className="extendField-card">
                  <div className="main-title">
                    <span>{messages('basic-5.key181')/*扩展字段*/}</span>
                    <Popover className="tool-tip" title={'图片类型字段暂不允许配置展示'}>
                      <Icon style={{marginLeft: '10px'}} type="info-circle-o"/>
                    </Popover>
                  </div>
                  <FormItem {...formLayout}>
                    {
                      getFieldDecorator('extendField', {
                        initialValue: extendInitValue,
                      })(
                        <Checkbox.Group className="checkbox-group" onChange={this.handleExtendChange}>
                          {this.renderExtendFieldCheckbox()}
                        </Checkbox.Group>
                      )
                    }
                  </FormItem>
                </div>
              </If>
              <div className="jods-info-card">
                <div className="main-title">{messages('basic-5.key419')/*岗位信息*/}</div>
                <FormItem {...formLayout}>
                  {
                    getFieldDecorator('jobInfo', {
                      initialValue: jobInfoInitValue,
                    })(
                      <Checkbox.Group options={jobInfoOption} className="checkbox-group" onChange={this.handleJobInfoChange}>
                      </Checkbox.Group>
                    )
                  }
                </FormItem>
              </div>
            </Form>
            <div>
              <Button type="primary" loading={loading}
                      onClick={this.handleSubmit}
                      htmlType="submit">
                {messages('common.save')/*保存*/}
              </Button>
              <Button onClick={this.handleCancel}
                      style={{marginLeft: 8}}>
                {messages('common.back')/*返回*/}
              </Button>
            </div>
          </Col>
          <Col span={9}>
            <IPhoneX type='iPhoneX' title={messages('basic-5.key465')/*个人信息*/}>
              <div className="card-background">
                <div className="main-card">
                  <div className="avatar-card">
                    <div className="avatar">
                      <img className="avatar-img" src={avatar} alt=""/>
                    </div>
                    <div className="edit-avatar">
                      <span className="edit">{messages('basic-5.key466')/*编辑头像*/}</span>
                      <img className="img" src={arrowImg} alt=""/>
                    </div>
                  </div>
                  <div
                    className={hasJobsInfo ? 'main-info-card have-bottom-line' : 'main-info-card'}>
                    <If value={basicShowMap['fullName']}>
                      <div className="name">
                        {userInfo.fullName || '-'}
                      </div>
                    </If>
                    <div className={hasBasicInfo ? 'detail-info margin-top12' : 'detail-info'}>
                      <If value={basicShowMap['employeeID']}>
                        <div className="job-id">
                          <img className="thumbnail-img" src={jobIdImg} alt=""/>
                          {userInfo.employeeID || '-'}
                        </div>
                      </If>
                      <If value={basicShowMap['mobile']}>
                        <div className="phone">
                          <img className="thumbnail-img" src={phoneImg} alt=""/>
                          {userInfo.mobile || '-'}
                        </div>
                      </If>
                      <If value={basicShowMap['email']}>
                        <div className="email">
                          <img className="thumbnail-img" src={emailImg} alt=""/>
                          {userInfo.email || '-'}
                        </div>
                      </If>
                    </div>
                    <div
                      className={(hasJobsInfo ? 'other-info padding-bottom' : 'other-info') + ' ' + (hasOtherInfo ? 'margin-top12' : '')}>
                      <If value={basicShowMap['employeeType']}>
                        <div>
                          {messages('basic-5.key382')/*人员类型*/ + '：' + (userInfo.employeeType ? userInfo.employeeType : '-')}
                        </div>
                      </If>
                      <If value={basicShowMap['directManagerName']}>
                        <div>
                          {messages('basic-5.key278')/*直属领导*/ + '：' + (userInfo.directManagerName ? userInfo.directManagerName : '-')}
                        </div>
                      </If>
                      <If value={basicShowMap['gender']}>
                        <div>
                          {messages('basic-5.key283')/*性别*/ + '：' + (userInfo.gender ? userInfo.gender : '-')}
                        </div>
                      </If>
                      <If value={basicShowMap['birthday']}>
                        <div>
                          {messages('basic-5.key282')/*生日*/ + '：' + (userInfo.birthday ? moment(userInfo.birthday)
                            .format('YYYY/MM/DD') : '-')}
                        </div>
                      </If>
                      <If value={basicShowMap['entryTime']}>
                        <div>
                          {messages('basic-5.key281')/*入职时间*/ + '：' + (userInfo.entryTime ? moment(userInfo.entryTime)
                            .format('YYYY/MM/DD') : '-')}
                        </div>
                      </If>
                      {this.renderExtendField()}
                    </div>
                  </div>
                  <div className="job-info-card">
                    <If value={hasJobsInfo}>
                      <div className="job-info-title">
                        {messages('basic-5.key419')/*岗位信息*/}
                      </div>
                    </If>
                    {this.renderPosition()}
                  </div>
                </div>
              </div>
            </IPhoneX>
          </Col>
        </Row>
      </div>

    );
  }
}

PersonInfoDisplay.contextTypes = {
  router: React.PropTypes.object
};

const wrappedPersonInfoDisplay = Form.create()(PersonInfoDisplay);

function mapStateToProps(state) {
  return {
    isOldCompany: state.login.isOldCompany,
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    currentPageRoute: state.main.currentPageRoute,
    language: state.main.language
  };
}

export default connect(mapStateToProps)(wrappedPersonInfoDisplay);
